package project_cmd

import (
	"errors"
	"fmt"
	"learning/gooop/spring/autogen/command"
	"learning/gooop/spring/autogen/common"
	"os"
	"strings"
)

// ProjectCmd defines a project with name and dir
type ProjectCmd struct {
	name string
	dir  string
}

// ProjectCmdBuilder parses cli input and creates a ProjectCmd instance
type ProjectCmdBuilder int

const gProjectCmdPrefix = "project "

var gErrorInvalidProjectCmd = errors.New("invalid project cmd")

func (me *ProjectCmd) String() string {
	return fmt.Sprintf("project %s %s", me.name, me.dir)
}

func (me *ProjectCmd) Apply(ctx command.ICmdContext) error {
	panic("implements me")
}

func (me *ProjectCmdBuilder) Build(line string) (error, command.ICmd) {
	if !common.Tokens.MatchString(line, gProjectCmdPrefix) {
		return nil, nil
	}

	line = strings.TrimSpace(line[len(gProjectCmdPrefix):])
	b, name := common.Tokens.MatchIdentifier(line)
	if !b {
		return gErrorInvalidProjectCmd, nil
	}

	line = line[len(name):]
	b, spaces := common.Tokens.MatchSpaces(line)
	if !b {
		return gErrorInvalidProjectCmd, nil
	}

	line = line[len(spaces):]
	b, dir := common.Tokens.MatchDir(line)
	if !b {
		return gErrorInvalidProjectCmd, nil
	}
	_, e := os.Stat(dir)
	if e != nil {
		return e, nil
	}

	return nil, &ProjectCmd{name, dir}
}
